package cn.edu.tju.se.base.web;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;


import javax.servlet.http.HttpServletRequest;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadController {

    @RequestMapping(value="/upload", method=RequestMethod.GET)
    public @ResponseBody String provideUploadInfo(HttpServletRequest request) {
        String filePath = request.getSession().getServletContext().getRealPath("/");
        return filePath;
    }

    @RequestMapping(value="/upload", method=RequestMethod.POST)
    public @ResponseBody String handleFileUpload(HttpServletRequest request,
            @RequestParam(value = "file") MultipartFile file){
    	String name = file.getOriginalFilename();
    	String prefix=name.substring(name.lastIndexOf(".")+1);
    	
        if  (!file.isEmpty()) {
            try {
            	String filePath = request.getSession().getServletContext().getRealPath("/");
            	File saveFile = new File(filePath+"/dd");
            	if  (!saveFile .exists()  && !saveFile .isDirectory())      
            	{       
            	    System.out.println("//不存在");  
            	    saveFile.mkdir();    
            	} else   
            	{  
            	    System.out.println("//目录存在");  
            	}  
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(filePath+"/"+name)));
                stream.write(bytes);
                stream.close();
                return "You successfully uploaded " ;
            } catch (Exception e) {
                return "You failed to upload " ;
            }
        } else {
            return "You failed to upload ";
        }
        //return "You failed to upload 123123";
    }

}